package com.f6.weixin.qiantai.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.f6.exceptions.BusinessException;
import com.f6.service.CommonService;
import com.f6.utils.SystemConstans;
import com.f6.vo.DBParameter;
import com.f6.weixin.utils.F6WXSessionUtil;
import com.f6.weixin.utils.WeiXinUtils;
import com.f6.weixin.vo.DishVO;
import com.f6.weixin.vo.OrderListVO;
import com.f6.weixin.vo.OrderVO;
import com.f6.weixin.vo.RouVO;
import com.f6.weixin.vo.UserVO;
import com.f6.weixin.vo.YinLiaoVO;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping(SystemConstans.QT)
public class OrderQTController {
	private Logger logger = LoggerFactory.getLogger(OrderQTController.class);
	private static int huoguo_price = 78;
	private static int yinliao_price = 4;
	private static int rou_price = 28;

	@Autowired
	private CommonService commonservice;

	@RequestMapping(value = "ordercreate", method = RequestMethod.POST)
	public ModelAndView ordercreate(HttpServletRequest request, HttpServletResponse response) throws BusinessException {
		String openid = request.getParameter("openid");
		String dishlistjson = request.getParameter("fdishlist");
		logger.info("enter ordercreate" + dishlistjson);
		OrderListVO orderlist = JSONObject.parseObject(dishlistjson, OrderListVO.class);
		F6WXSessionUtil.getInstance().put(SystemConstans.SESSION_ATTR_ORDER + "_" + openid, orderlist);
		// request.getSession().setAttribute(SystemConstans.SESSION_ATTR_ORDER,
		// orderlist);

		logger.info("-----------" + orderlist.getHuoguolist().size());
		// String openid = F6WebUtil.getCurrentWeixinUserID(request);
		UserVO user = (UserVO) F6WXSessionUtil.getInstance().get(SystemConstans.SESSION_ATTR_USER + "_" + openid);

		if (user == null) {
			throw new UnknownSessionException("no user!!!");
		}
		ModelAndView mv = new ModelAndView();
		// String add1 = user.getAddress1();
		// String add2 = user.getAddress2();
		// String add3 = user.getAddress3();
		//
		//
		// mv.addObject("address1", add1);
		// mv.addObject("address2", add2);
		// mv.addObject("address3", add3);
		// // 是否需要新增地址
		// if (F6SystemUtils.isStrNull(add1)) {
		// mv.addObject("newaddress", 1);
		// } else {
		// mv.addObject("newaddress", 0);
		// }

		mv.addObject("dish", orderlist);
		List<String> shoplist = new ArrayList<String>();
		shoplist.add("店铺1");
		shoplist.add("店铺2");
		shoplist.add("店铺3");
		int totalprice = getTotalPrice(orderlist);
		mv.addObject("totalprice", totalprice);
		mv.addObject("shoplist", shoplist);
		mv.addObject("openid", openid);
		mv.setViewName("qt/ordercreate");
		return mv;
	}

	private int getTotalPrice(OrderListVO orderlist) {
		int totalprice = 0;
		List<DishVO> huoguolist = orderlist.getHuoguolist();
		if (huoguolist != null && huoguolist.size() > 0) {
			for (DishVO huoguo : huoguolist) {
				totalprice += huoguo.getNoOfDish() * huoguo_price;
			}
		}
		List<RouVO> roulist = orderlist.getRoulist();
		if (roulist != null && roulist.size() > 0) {
			for (RouVO rou : roulist) {
				totalprice += Integer.parseInt(rou.getNo()) * rou_price;
			}
		}
		List<YinLiaoVO> yinliaolist = orderlist.getYinliaolist();

		if (yinliaolist != null && yinliaolist.size() > 0) {
			for (YinLiaoVO yinliao : yinliaolist) {
				String nameYinliao = yinliao.getName();
				if (nameYinliao.equals("矿泉水")) {
					totalprice += Integer.parseInt(yinliao.getNo()) * rou_price;
				} else {
					totalprice += Integer.parseInt(yinliao.getNo()) * rou_price;
				}

			}
		}
		return totalprice;
	}

	@RequestMapping(value = "orderpreview", method = RequestMethod.GET, produces = "application/text;charset=UTF-8")
	public ModelAndView orderpreview() throws IOException, BusinessException {
		logger.info("enter order list");
		ModelAndView mv = new ModelAndView();
		mv.setViewName("ht/orderlist");

		Map paramap = new HashMap<String, String>();
		DBParameter dbparam = new DBParameter();
		dbparam.setAction("getAllOrders");
		dbparam.setModule("putong.Order");
		dbparam.setParameter(paramap);

		List<Map<String, ?>> list = commonservice.queryMore(dbparam);
		// List<Dish> list = new ArrayList<Dish>();
		logger.info("获取列表:" + list.size());
		mv.addObject("orderlist", list);
		return mv;
	}

	@RequestMapping(value = "ordersave", method = RequestMethod.POST)
	public ModelAndView ordersave(HttpServletRequest request) throws IOException, BusinessException {

		logger.info("enter orderconfirm");
		ModelAndView mv = new ModelAndView();
		String openid = request.getParameter("openid");
		OrderListVO orderlist = (OrderListVO) F6WXSessionUtil.getInstance().get(SystemConstans.SESSION_ATTR_ORDER + "_" + openid);
		String address = request.getParameter("shopname");
		String contacttel = request.getParameter("contacttel");
		String contactname = request.getParameter("contactname");
		String memo = request.getParameter("memop");
		logger.info(address + "==" + contacttel + "==" + memo);
		Map paramap = new HashMap<String, String>();
		DBParameter dbparam = new DBParameter();
		dbparam.setAction("insert");
		dbparam.setModule("putong.Order");

		ObjectMapper objectMapper = new ObjectMapper();
		paramap.put("parametertype", "com.f6.weixin.vo.OrderVO");
		OrderVO vo = new OrderVO();

		vo.setReceiverAddress(address);

		vo.setReceiverPhone(contacttel);

		vo.setOrderStatus(SystemConstans.ORDER_STATUS_NO_PAY);

		vo.setIdCode(openid);

		vo.setBranchCode("1");

		vo.setCreatedBy("admin");
		vo.setCreatedDate(new Date());

		vo.setUpdatedBy("admin");
		vo.setUpdatedDate(new Date());

		vo.setMem(memo);

		vo.setContactName(contactname);

		vo.setOrderContent(objectMapper.writeValueAsString(orderlist));
		String totalprice = String.valueOf(getTotalPrice(orderlist));
		vo.setTotalPrice(totalprice);

		dbparam.setInsertObj(vo);

		Object result = commonservice.insert(dbparam);
		logger.info("oresult:" + result);
		String orderCode = ((OrderVO) result).getOrderCode();
		logger.info("order code:" + orderCode);
		String payurl = WeiXinUtils.createOAuthURI(SystemConstans.WEXIN_DOMAIN + SystemConstans.PAY_TEST + "/pay.do?ordercode=" + orderCode
				+ "&openid=" + openid + "&totalprice=" + totalprice);
		String redirecturl = SystemConstans.PAY_TEST + "/pay.do?ordercode=" + orderCode + "&openid=" + openid;
		logger.info("redirect to :" + redirecturl);
		mv.setViewName("redirect:" + payurl);

		return mv;
	}

	@RequestMapping(value = "paytest", method = RequestMethod.GET)
	public String paytest(HttpServletRequest request) throws IOException, BusinessException {
		ModelAndView mv = new ModelAndView();
		String payurl = WeiXinUtils.createOAuthURI(SystemConstans.WEXIN_DOMAIN + SystemConstans.PAY_TEST + "/pay.do");
		logger.info("redirect to :" + payurl);
		return "redirect:" + payurl;
	}

}
